<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == 'add' ? '新建宣讲报送' : '编辑宣讲报送' }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="140px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="宣讲主题" prop="subject">
          <el-select v-model="ruleForm.subject" placeholder="请选择宣讲主题">
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
            <template #footer>
              <el-button text bg @click="addSubject"> 需自定义宣讲主题？去新增主题 </el-button>
            </template>
          </el-select>
        </el-form-item>

        <el-form-item label="宣讲类别" prop="preachType">
          <el-select v-model="ruleForm.preachType" placeholder="请选择宣讲类别">
            <el-option
              v-for="item in preachTypeList"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
            <template #footer>
              <el-button text bg @click="addPreachType"> 需自定义宣讲类别？去新增类别 </el-button>
            </template>
          </el-select>
        </el-form-item>

        <el-form-item label="上报单位" prop="studyUnitName">
          <el-input v-model="ruleForm.studyUnitName" placeholder="请输入上报单位" disabled></el-input>
        </el-form-item>

        <el-form-item label="宣讲地点" prop="location">
          <el-input v-model="ruleForm.location" placeholder="请输入宣讲地点"></el-input>
        </el-form-item>

        <el-form-item label="宣讲员姓名" prop="speaker">
          <el-input v-model="ruleForm.speaker" placeholder="请输入宣讲员姓名"></el-input>
        </el-form-item>

        <el-form-item label="宣讲员单位及职务" prop="speakerUnit">
          <el-input v-model="ruleForm.speakerUnit" placeholder="请输入宣讲员单位及职务"></el-input>
        </el-form-item>

        <!-- <el-form-item label="宣讲员职务" prop="duties">
          <el-input v-model="ruleForm.duties" placeholder="请输入宣讲员职务"></el-input>
        </el-form-item> -->

        <el-form-item label="宣讲题目" prop="submittedName">
          <el-input v-model="ruleForm.submittedName" placeholder="请输入宣讲题目"></el-input>
        </el-form-item>

        <el-form-item label="宣讲时间" prop="preachTime">
          <el-date-picker
            v-model="ruleForm.preachTime"
            type="date"
            placeholder="请选择宣讲时间"
            value-format="YYYY-MM-DD"
            clearable
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="宣讲对象" prop="preachPersons">
          <el-input v-model="ruleForm.preachPersons" placeholder="请输入宣讲对象"></el-input>
        </el-form-item>

        <el-form-item label="受众人数" prop="preachPersonNum">
          <el-input-number
            v-model="ruleForm.preachPersonNum"
            controls-position="right"
            style="width: 100%"
            placeholder="请输入受众人数"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="附件" prop="picture">
          <upload-file-result :fileList="fileList" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadEvent">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传附件
          </el-button>
          <span style="margin-left: 10px"
            >请上传不超过20M的文件，格式：jpg/jpeg/png/mp4/doc/docx/xls/xlsx/ppt/pptx/pdf</span>
        </el-form-item>

        <el-form-item class="add-button">
          <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="buttonLoading">
            {{ $route.query.type == 'add' ? '新增' : '编辑' }}
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" :loading="buttonLoading">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: 'backendPublicizeSubmittedAdd' }
</script>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { UploadFilled, Picture, ArrowDownBold } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index'
import { format } from '@/plugins/moment.js'
import { uploadFile } from '@/utils/file.js'
import { ContentTypeEnum } from '@/enums/httpEnum'
import { testFileType, testFileSize, isJsonString } from '@/utils/backend.js'
import { useAuthStore } from '@/stores/modules/auth.js'
import uploadFileResult from "@/components/backend/fileList.vue"

/* 路由 */
const route = useRouter()

/* 用户信息 */
const authStore = useAuthStore()

onMounted(() => {
  if (route.currentRoute.value.query.id) {
    getSubmittedDetail()
  }

  getSubjectList()

  /* 宣讲主题跳转过来，默认选中此主题 */
  if(route.currentRoute.value.query.subjectId){
    ruleForm.value.subject = route.currentRoute.value.query.subjectId
  }

  getPreachTypeList()

  /* 宣讲类别跳转过来，默认选中此类别 */
  if(route.currentRoute.value.query.typeId){
    ruleForm.value.preachType = route.currentRoute.value.query.typeId
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getSubmittedDetail = () => {
  loading.value = true
  http
    .$GET('/PreachM/GetPreachSubmittedDetailById', { Id: route.currentRoute.value.query.id })
    .then((res) => {
      loading.value = false
      if (res.isError) return
      if (!res.result) return

      /* 赋值 */
      Object.keys(ruleForm.value).forEach((key) => {
        if (res.result[key] != null) {
          ruleForm.value[key] = res.result[key]
        }
      })

      /* 处理数值 */
      ruleForm.value.preachPersonNum = Number(res.result.preachPersonNum)

      /* 处理日期 */
      ruleForm.value.preachTime = format(res.result.preachTime)

      /* 动态封面图片路径 */
      if (!isJsonString(res.result.picture)) {
        fileList.value = []
        ruleForm.value.picture = ''
        return
      }
      if (res.result.picture != '') {
        let picture = JSON.parse(res.result.picture)

        if (picture.filePathArray) {
          fileList.value = picture.filePathArray
        } else {
          fileList.value = []
          ruleForm.value.picture = ''
        }
      }
    })
    .catch((err) => {
      loading.value = false
      ElMessage.warning('查询失败')
    })
}

/* 禁选提醒日期 */
const disabledDate = (time) => {
  return time.getTime() < new Date() - 24 * 60 * 60 * 1000
}

/* 宣讲主题 */
const subjectList = ref([])
const subjectPageIndex = ref(1)
const subjectPageType = ref(200)
const getSubjectList = () => {
  let params = {
    pageIndex: subjectPageIndex.value,
    pageSize: subjectPageType.value
  }
  http.$POST(`/PreachM/GetPreachFillingSubjectInfoList`, params).then(res => {
    subjectList.value = subjectList.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      subjectPageIndex.value = subjectPageIndex.value + 1
      getSubjectList()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 新建主题 */
const addSubject = () => {
  route.push({
    path: '/backend/publicize-submitted-theme',
  })
}

/* 宣讲类别 */
const preachTypeList = ref([])
const preachTypePageIndex = ref(1)
const preachTypePageType = ref(200)
const getPreachTypeList = () => {
  let params = {
    pageIndex: preachTypePageIndex.value,
    pageSize: preachTypePageType.value
  }
  http.$POST(`/PreachM/GetPreachFillingTypeInfoList`, params).then(res => {
    preachTypeList.value = preachTypeList.value.concat(res.result.dataLst)
    if(res.result.countAll > res.result.pageIndex * res.result.pageSize){
      preachTypePageIndex.value = preachTypePageIndex.value + 1
      getPreachTypeList()
    }
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 新建类别 */
const addPreachType = () => {
  route.push({
    path: '/backend/publicize-submitted-type',
  })
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单数据 */
const ruleForm = ref({
  id: '',
  subject: '',
  preachType: '',
  speakerUnit: '',
  location: '',
  speaker: '',
  studyUnit: authStore.userInfo.orgId ? authStore.userInfo.orgId : "",
  studyUnitName: authStore.userInfo.orgName ? authStore.userInfo.orgName : '',
  /* duties: '', */
  /* subject: '', */
  preachTime: '',
  preachPersons: '',
  preachPersonNum: null,
  picture: '',
  submittedName: "",
})

/* 附件列表 */
const fileList = ref([])
/* 是否有上传图片 */
const isUploadFile = ref(false)

/* 表单校验规则 */
const rules = reactive({
  subject: [{ required: true, message: '请选择宣讲主题', trigger: 'change' }],
  preachType: [{ required: true, message: '请选择宣讲类别', trigger: 'change' }],
  appontUnit: [{ required: true, message: '请输入上报单位', trigger: 'blur' }],
  location: [
    { required: true, message: '请输入宣讲地点', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur' }
  ],
  speaker: [
    { required: true, message: '请输入宣讲员姓名', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur' }
  ],
  speakerUnit: [
    { required: true, message: '请输入宣讲员单位及职务', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur' }
  ],
  studyUnitName: [
    { required: true, message: '无上级单位不允许填报', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur' }
  ],
  /* duties: [
    { required: true, message: '请输入宣讲员职务', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur' }
  ], */
  submittedName: [
    { required: true, message: '请输入宣讲题目', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur' }
  ],
  preachTime: [{ required: true, message: '请输入宣讲时间', trigger: 'change' }],
  preachPersons: [
    { required: true, message: '请输入宣讲对象', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur' }
  ],
  preachPersonNum: [{ required: true, message: '请输入受众人数', trigger: 'change' }]
})

/* 点击上传文件 */
const uploadEvent = async () => {
  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG,.mp4,.MP4,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.DOC,.DOCX,.XLS,.XLSX,.PPT,.PPTX,.PDF"

  uploadFile({ accept: fileType, multiple: true }).then((res) => {
    /* 文件格式判断 */
    if (!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG|mp4|MP4|doc|docx|xls|png|xlsx|ppt|pptx|pdf|DOC|DOCX|XLS|XLSX|PPT|PPTX|PDF)$/)) {
      ruleForm.value.picture = ''
      fileList.value = []
      isUploadFile.value = false
      return
    }
    /* 文件大小判断 */
    if (!testFileSize(res, 10 * 1024 * 1024)) {
      ruleForm.value.picture = ''
      fileList.value = []
      isUploadFile.value = false
      return
    }
    /* 文件个数判断 */
    /* if (fileList.value.length >= 3 || res.length > 3 || fileList.value.length + res.length > 3) {
      return ElMessage.error('不能上传超过3张图片')
    } */

    if (res) {
      isUploadFile.value = true
      ruleForm.value.picture = res
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate('picture')
      /* 预览缩略图 */
      /* const list = Array.from(res).map((el) => {
        const temp = reactive({
          file: el,
          url: ''
        })
        getimgurl(temp).then((urlA) => (temp.url = urlA))
        return temp
      }) */
      fileList.value = res
    }
  })
}

const getimgurl = (item) => {
  return new Promise((resolve) => {
    var reader = new FileReader()
    reader.readAsDataURL(item.file)
    reader.onload = (e) => {
      resolve(e.target.result)
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if (route.currentRoute.value.query.type == 'add') {
        delete ruleForm.value.id
      }

      /* 未更新图片时不传值 */
      if (!isUploadFile.value) {
        delete ruleForm.value.picture
      }

      /* 参数处理 */
      const formData = new FormData()
      for(let k in ruleForm.value) {
        if( k != 'picture') {
          formData.append(k, ruleForm.value[k]);
        } else {
          if(isUploadFile.value){
            for(let j in ruleForm.value[k]) {
              if( j < ruleForm.value[k].length ) {
                formData.append('picture', ruleForm.value[k][j]);
              }
            }
          }
        }
      }

      if(authStore.auth_token){
        formData.append('authToken', authStore.auth_token)
      }

      http
        .$POST(
          '/PreachM/AddOrUpdatePreachSubmittedInfo',
          formData
        )
        .then((res) => {
          buttonLoading.value = false
          if (res.IsError) {
            ElMessage({
              type: 'warning',
              message: res.message
            })
          } else {
            ElMessage({
              type: 'success',
              message: '操作成功'
            })
            route.push({
              path: '/backend/publicize-submitted'
            })
          }
        })
        .catch((err) => {
          buttonLoading.value = false
          ElMessage({
            type: 'warning',
            message: '操作失败'
          })
        })
    } else {
      ElMessage({
        type: 'warning',
        message: '请先完成必填项'
      })
    }
  })
}

/* 重置 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  imageUrl.value = ''
  isUploadFile.value = false
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: '/backend/publicize-submitted',
    query: route.currentRoute.value.query.currentPage
      ? { currentPage: route.currentRoute.value.query.currentPage }
      : {}
  })
}
</script>

<style lang="scss" scoped>
@import '@/assets/styles/backendElement.scss';
</style>
